package com.learning.optimize.jdk.proxy.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * ClassName: ProxyUtil
 * Description: 获取代理对象的工具类
 * Date: 2018/7/25 9:27 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ProxyUtil {

    /**
     * 得到代理对象
     *
     * @param target
     * @param handle
     * @return
     */
    public static Object getProxy(Object target, InvocationHandler handle) {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), handle);

    }


    /**
     * 得到代理对象
     *
     * @param target
     * @param advice
     * @return
     */
    public static Object getProxy(final Object target, final Advice advice) {

        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy1, method, args) -> {
                    advice.before(method);
                    Object object = method.invoke(target, args);
                    advice.after(method);
                    return object;
                });

        return proxy;

    }

}
